package com.mall.czlr.app.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mall.czlr.app.model.Token;
import com.mall.czlr.base.common.Const;
import com.mall.czlr.base.entity.UserContext;
import com.mall.czlr.base.exception.BaseException;
import com.mall.czlr.base.interceptor.SecurityInterceptor;
import com.mall.czlr.base.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component("CoreAuthenticator")
public class UserAuthenticator implements SecurityInterceptor.Authenticator {

    private final ITokenService tokenService;

    @Autowired
    public UserAuthenticator(ITokenService tokenService) {
        this.tokenService = tokenService;
    }


    @Override
    public void process(HttpServletRequest httpServletRequest) {
        String token = SecurityInterceptor.getRequiredParam(httpServletRequest, "token");
        Token tokenModel = tokenService.selectOne(new EntityWrapper<Token>().eq("token", token));
        if (tokenModel == null) {
            Assert.exception(BaseException.ERROR_AUTH_FAIL, "invalid token");
        }

        UserContext userContext = new UserContext();
        userContext.setUserId(tokenModel.getUserId());
        userContext.setUserType(tokenModel.getUserType());

        httpServletRequest.setAttribute(Const.REQUEST_ATTR_KEY_USER_CONTEXT, userContext);
        httpServletRequest.setAttribute(Const.REQUEST_ATTR_KEY_ACCESS_TOKEN, token);
    }
}
